<!DOCTYPE html>
<html>
<head>
    <title>简易聊天Demo</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no">
    <link href="https://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/webSocketDemo.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="title">简易聊天demo</div>
    <div class="content">
        <div class="show-area"></div>
        <div class="write-area">
            <div>
                <button class="btn btn-default send">发送</button>
            </div>
            <div><input name="name" id="name" type="text" placeholder="input your name"></div>
            <div>
                <textarea name="message" id="message" cols="38" rows="4" placeholder="input your message..."></textarea>
            </div>
        </div>
    </div>
</div>

<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script>
    $(function () {
        var lockReconnect = false; //避免重复连接
        var userId = "user" + new Date().getMilliseconds();
        var wsurl = 'ws://127.0.0.1:8080/websocketChatRoom/user' + userId;
        var websocket;
        var i = 0;
        if (window.WebSocket) {
            doConnect();//连接
            function send() {
                var name = $('#name').val();
                var message = $('#message').val();
                if (!name) {
                    alert('请输入用户名!');
                    return false;
                }
                if (!message) {
                    alert('发送消息不能为空!');
                    return false;
                }
                var msg = {
                    message: message,
                    name: name
                };
                try {
                    websocket.send(JSON.stringify(msg));
                } catch (ex) {
                    console.log(ex);
                }
            }

            //按下enter键发送消息
            $(window).keydown(function (event) {
                if (event.keyCode == 13) {
                    console.log('user enter');
                    send();
                }
            });

            //点发送按钮发送消息
            $('.send').bind('click', function () {
                send();
            });

        }
        else {
            alert('该浏览器不支持web socket');
        }

        function getJSON(str) {
            if (typeof str == 'string') {
                try {
                    return JSON.parse(str);
                } catch(e) {
                    return null;
                }
            }
        }

        function reconnect() {
            if (lockReconnect) return;
            lockReconnect = true;
            //没连接上会一直重连，设置延迟避免请求过多
            setTimeout(function() {
                try {
                    doConnect();
                    lockReconnect = false;
                } catch (e) {
                    reconnect()
                }
            }, 2000);
        }

        function  doConnect() {
            websocket = new WebSocket(wsurl);
            //连接建立
            websocket.onopen = function (evevt) {
                console.log("Connected to WebSocket server.");
                $('.show-area').append('<p class="bg-info message"><i class="glyphicon glyphicon-info-sign"></i>Connected to WebSocket server!</p>');
            }
            //收到消息
            websocket.onmessage = function (event) {
                var msg = getJSON(event.data); //解析收到的json消息数据
                var type = msg.type; // 消息类型
                var umsg = msg.message; //消息文本
                var uname = msg.name; //发送人
                i++;
                if (type == 'usermsg') {
                    $('.show-area').append('<p class="bg-success message"><i class="glyphicon glyphicon-user"></i><a name="' + i + '"></a><span class="label label-primary">' + uname + ' : </span>' + umsg + '</p>');
                }
                if (type == 'system') {
                    $('.show-area').append('<p class="bg-warning message"><a name="' + i + '"></a><i class="glyphicon glyphicon-info-sign"></i>' + umsg + '</p>');
                }

                $('#message').val('');
                window.location.hash = '#' + i;
            }

            //发生错误
            websocket.onerror = function (event) {
                i++;
                console.log("Connected to WebSocket server error");
                $('.show-area').append('<p class="bg-danger message"><a name="' + i + '"></a><i class="glyphicon glyphicon-info-sign"></i>Connect to WebSocket server error.</p>');
                //重连
                reconnect();
            }

            //连接关闭
            websocket.onclose = function (event) {
                i++;
                console.log('websocket Connection Closed. ');
                $('.show-area').append('<p class="bg-warning message"><a name="' + i + '"></a><i class="glyphicon glyphicon-info-sign"></i>websocket Connection Closed.</p>');
                //断线重连
                reconnect();
                //window.location.hash = '#' + i;
            }
        }
    });


</script>
</body>
</html>